package com.yugong.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.yugong.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理类
 *
 * @author yugong
 * @date 2024/2/9
 */
@ControllerAdvice(basePackages = "com.yugong.controller")
public class GlobalExceptionHandler {
    private static final Log log = LogFactory.get();

    /**
     * 统一异常处理@ExceptionHandler,主要用于Exception
     *
     * @param request   请求
     * @param exception 统一异常
     * @return json字符串的异常信息
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(HttpServletRequest request, Exception exception) {
        log.error("异常信息：", exception);
        return Result.error();
    }

    /**
     * 普通异常
     *
     * @param request         请求
     * @param customException 普通异常类
     * @return json字符串的异常信息
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result customError(HttpServletRequest request, CustomException customException) {
        return Result.error(request, customException.getMsg());
    }
}
